package com.leoman.plz_p.presenter;

import android.text.TextUtils;

import com.leoman.plz_p.interfaces.PersonalInfoView;
import com.leoman.plz_p.module.api.UserApi;
import com.leoman.plz_p.module.bean.BaseData;
import com.leoman.plz_p.module.bean.MapData;
import com.leoman.plz_p.module.bean.UploadCallBackBean;
import com.leoman.plz_p.module.bean.User;
import com.leoman.plz_p.subscriber.ResponseSubscriber;
import com.leoman.plz_p.utils.UserHelper;

import java.io.File;

import cn.com.corelib.api.RequestBodyCreator;
import cn.com.corelib.api.ResponseTransformer;
import cn.com.corelib.base.BasePresenter;

public class PersonalInfoPresenter extends BasePresenter<PersonalInfoView> {

    private UserApi userApi;

    @Override
    protected void onViewAttach() {
        super.onViewAttach();
        userApi=getApi(UserApi.class);
    }

    public void editUser(final String headImage, final String nickName, final String address,String addressName, final String idCard, final String phone){
        getView().showLoading();
        userApi.editUser(UserHelper.getToken(),headImage,nickName,address,addressName,idCard,phone).compose(new ResponseTransformer<>(this.<BaseData>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<BaseData>(view) {
                    @Override
                    public void success(BaseData mapDataBaseData) {
                        User user=UserHelper.getSavedUser();
                        if (TextUtils.isEmpty(headImage)){
                            user.setHeadimg(headImage);
                        }
                        if (TextUtils.isEmpty(nickName)){
                            user.setNickname(nickName);
                        }
                        if (TextUtils.isEmpty(idCard)){
                            user.setIdentity(idCard);
                        }
                        if (TextUtils.isEmpty(phone)){
                            user.setPhone(phone);
                        }
                        UserHelper.saveUser(user);
                        view.editSuccess();
                    }
                });
    }

    public void uploadUserHead(File file){
        getView().showLoading();
        userApi.uploadImage(RequestBodyCreator.create(UserHelper.getToken()), RequestBodyCreator.create(file))
                .compose(new ResponseTransformer<>(this.<BaseData<MapData<UploadCallBackBean>>>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<BaseData<MapData<UploadCallBackBean>>>(view) {
                    @Override
                    public void success(BaseData<MapData<UploadCallBackBean>> data) {
                        view.obtainUploadImageSuccess(data.data.list.get(0).getPath());
                    }
                });
    }

    @Override
    public void onStart() {

    }
}